<template>
   <!-- 面包屑导航区域-->
    <div><el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片视图区域-->
  <el-card>
       <!-- 搜索添加-->
       <el-row :gutter="20">
      <el-col :span="8">
          <el-input placeholder="请输入内容" 
          v-model="queryinfo.query" clearable @clear="getuserlist">
           <el-button slot="append" icon="el-icon-search" @click="getuserlist"></el-button>
            </el-input>
      </el-col>
      <el-col :span="4">
          <el-button type="primary" @click="adddialogVisible=true">添加用户 </el-button>
      </el-col>
    </el-row>
    <!-- 用户列表区域-->
    <el-table :data="userlist" border stripe>
        <el-table-column type="index"> </el-table-column>
      <el-table-column prop="username" label="姓名"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userstatuschange(scope.row)" ></el-switch>                           
          </template> 
      </el-table-column>
      <el-table-column label="操作" width="180px"> 
          <template slot-scope="scope">
              <!-- 修改按钮-->
            <el-button size="mini" type="primary" icon="el-icon-edit"
            @click="showeditdialog(scope.row.id)" ></el-button>
            <!-- 删除按钮-->
            <el-button size="mini" type="danger" icon="el-icon-delete"
            @click="removeuserbyid(scope.row.id)"></el-button>
            <!-- 分配角色按钮-->
            <el-tooltip :enterable="false"  effect="dark" content="分配角色" placement="top">
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="setrole(scope.row)"></el-button>
            </el-tooltip>                           
          </template>
          </el-table-column> 

       <!-- 分页区域-->         
    </el-table>  
     <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryinfo.pagenum"
      :page-sizes="[1,2,5,10]"
      :page-size="queryinfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
</el-card>
 <!-- 添加用户的对话框-->
<el-dialog
  title="添加用户"
  :visible.sync="adddialogVisible"
  width="50%"
  @close="adddialogclose">
   <!-- 内容主体区-->
  <span><el-form :model="addForm" :rules="addFormrules"
   ref="addFormref" label-width="70px" class="demo-ruleForm">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
    <el-form-item label="密码" prop="password">
    <el-input v-model="addForm.password"></el-input>
  </el-form-item>
    <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
    <el-form-item label="手机" prop="mobile">
    <el-input v-model="addForm.mobile"></el-input>
  </el-form-item>
  </el-form></span>

   <!-- 底部区域-->
  <span slot="footer" class="dialog-footer">
    <el-button @click="adddialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="adduser">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="修改用户"
  :visible.sync="editdialogVisible"
  width="50%"
  @close="editdialogclose"
  >
   <!-- 内容主体区-->
  <span><el-form :model="editfrom" :rules="editFormrules"
   ref="editFormref" label-width="70px" >
  <el-form-item label="用户名" >
    <el-input v-model="editfrom.username" disabled></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
    <el-input v-model="editfrom.email"></el-input>
  </el-form-item>
    <el-form-item label="手机" prop="mobile">
    <el-input v-model="editfrom.mobile"></el-input>
  </el-form-item>
  </el-form></span>

   <!-- 底部区域-->
  <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="edituserinfo">确 定</el-button>
  </span>
</el-dialog>
 <!-- 分配角色-->
<el-dialog
  title="分配角色"
  :visible.sync="setroledialogVisible"
  width="50%"
  :before-close="handleClose">
  <div>
    <p>当前的用户:{{userinfo.username}}</p>
    <p>当前的角色:{{userinfo.role_name}}</p>
    <p>分配新角色：
      <el-select v-model="selectroleid" placeholder="请选择">
    <el-option
      v-for="item in rolelist"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
    </p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setroledialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setrolrinfo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
export default {
    data() {
        // 验证邮箱的规则
         var checkemail = (rule, value, callback) => {
             const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (regEmail.test(value)) {
            // 合法邮箱
          return callback();
        }
        return callback(new Error('邮箱不合法'));
      };
      // 验证手机号的规则
         var checkemobile = (rule, value, callback) => {
        const regmobile = /^(((13[0-9])|(14[5-7])|(15[0-9])|(17[0-9])|(18[0-9]))+\d{8})$/;
        if (regmobile.test(value)) {
            // 合法邮箱
          return callback();
        }
        return callback(new Error('手机号不合法'));
      };
        return {
            // 获取用户列表的参数对象
            queryinfo: {
                query:'',
                // 当前的页数
                pagenum:1,
                // 当前每页显示多少条数据
                pagesize:2
            },
            userlist: {},
            total:0,
            // 控制添加对话框的显示与隐藏
            adddialogVisible:false,
            // 添加用户的表单数据
            addForm: {
                username:'',
                password:'',
                email:'',
                mobile:''               
            },
            // 添加表单的验证规则对象
            addFormrules: {
                 username: [
                     { required: true, message: '请输入用户名', trigger: 'blur' },
                     { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                     { required: true, message: '请输入密码', trigger: 'blur' },
                     { min: 6, max: 15, message: '用户名长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email: [
                     { required: true, message: '请输入邮箱', trigger: 'blur' },
                     { validator: checkemail, trigger: 'blur' }
                ],
                mobile: [
                     { required: true, message: '请输入手机号', trigger: 'blur' },
                     { validator: checkemobile, trigger: 'blur' }
                ]
            },
            // 控制修改永华对话框的显示与隐藏
            editdialogVisible:false,
            // 查询到的用户信息对象
            editfrom: {},
            // 修改表单的验证规则对象
            editFormrules: {
                email: [
                     { required: true, message: '请输入邮箱', trigger: 'blur' },
                     { validator: checkemail, trigger: 'blur' }
                ],
                mobile: [
                     { required: true, message: '请输入手机号', trigger: 'blur' },
                     { validator: checkemobile, trigger: 'blur' }
                ]
            },
            // 控制分配角色对话框
            setroledialogVisible:false,
            // 需要分配角色的用户信息
            userinfo:{},
            // 所有角色的列表
            rolelist:{},
            // 已经选中的角色值
            selectroleid:''               
        }
    },
    created() {
        this.getuserlist()
    },
    methods: {
        async getuserlist() {
            const { data:res } = await this.$http.get('users', { params: this.queryinfo })
            if (res.meta.status !== 200) {
                return this.$message.error('获取用户列表失败')
            }
            this.userlist = res.data.users
            this.total = res.data.total
            console.log(res)
            console.log(this.userlist)
        },
        // 监听pagesize改变的事件
        handleSizeChange(newsize) {
            // console.log(newsize)
            this.queryinfo.pagesize = newsize
            this.getuserlist() 
        },
        // 监听页码值 改变的事件
        handleCurrentChange(newpage) {
            // console.log(newpage)
            this.queryinfo.pagenum = newpage
            this.getuserlist()
        },
        async userstatuschange(userinfo) {
            // console.log(userinfo)
            const { data:res } = 
            await this.$http.put(`users/${userinfo.id}/state/${userinfo.my_state}`)
            // console.log(res)
            if (res.meta.status !== 200) {
                userinfo.my_state = !userinfo.my_state
                return this.$message.error('用户更新失败')
            }
            this.$message.success('用户更新成功')
        },
        // 监听添加用户对话框的关闭事件
        adddialogclose() {
            this.$refs.addFormref.resetFields()
            // console.log('重置')
        },
        // 点击按钮，添加新用户
        adduser() {
            this.$refs.addFormref.validate(async valid => {
                if (!valid) return
                // 可以发起对添加用户的网络请求
                const { data:res } = await this.$http.post('users', this.addForm)
                if (res.meta.status !== 201) {
                    this.$message.error('用户添加失败')
                }
                this.$message.success('用户添加成功')
                // 隐藏对话框
                this.adddialogVisible = false
                console.log(this.addForm)
                // 重新获得用户列表数据
                this.getuserlist()
            })
        },
        // 展示编辑用户的对话框
        async showeditdialog(id) {
            this.editdialogVisible = true
            const { data:res } = await this.$http.get('users/' + id)
            if (res.meta.status !== 200) {
                    this.$message.error('查询用户信息失败')
                }
            this.$message.success('查询用户信息成功')
            this.editfrom = res.data    
        },
        // 监听修改用户对话框的关闭事件
        editdialogclose() {
            this.$refs.editFormref.resetFields()
        },
        // 修改用户信息并提交
         edituserinfo() {
            this.$refs.editFormref.validate(async valid => {
                // console.log(valid)
                if (!valid) return
                const { data:res } = await this.$http.put('users/' + this.editfrom.id,
                { email: this.editfrom.email,
                mobile: this.editfrom.mobile })
                if (res.meta.status !== 200) {
                    this.$message.error('更新用户信息失败')
                }
            // 关闭对话框
            this.editdialogVisible = false
            // 刷新数据列表
            this.getuserlist()
            // 提示成功
            this.$message.success('查询用户信息成功') 
            })           
         },
         // 根据用户id删除信息
         async removeuserbyid(id) {
         // 提示用户是否删除
         const ress = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((error) => {
          return error         
        });
        // 如果用户确定删除，返回值为字符串confirm
        if (ress !== 'confirm') {
          this.$message.info('已经取消删除')
        }
        const { data:res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
            return this.$message.error('删除用户信息失败')
         }
         this.getuserlist()
         this.$message.success('删除用户信息成功')       
    },
         // 分配角色
         async setrole(userinfo) {
           this.setroledialogVisible = true
           this.userinfo = userinfo
           const { data:res } = await this.$http.get('roles')
           if (res.meta.status !== 200) {
            return this.$message.error('获取角色列表失败')
         }
         this.rolelist = res.data      
         },
         // 设置新角色
         async setrolrinfo() {
           this.setroledialogVisible = false
           if (!this.selectroleid) {
             return this.$message.error('请选择要分配的角色')
           }
           const { data:res } = await this.$http.put(`users/${this.userinfo.id}/role`, { rid: this.selectroleid })
           if (res.meta.status !== 200) {
             console.log('11111' + res + this.userinfo.id + this.selectroleid)
            return this.$message.error('获取角色列表失败')
         }
         this.getuserlist()
         }
}
}
</script>
<style lang="less" scoped>
</style>
